/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ipfms.stripes.property;

import able.stripes.JSP;
import com.google.inject.Inject;
import ipfms.dao.BuildingDAO;
import ipfms.dao.BuildingImgDAO;
import ipfms.manager.BuildingManager;
import ipfms.manager.InboxManager;
import ipfms.model.Building;
import ipfms.model.BuildingImg;
import ipfms.model.Inbox;
import ipfms.model.InfoAudit;
import ipfms.model.Pengguna;
import ipfms.stripes.BaseActionBean;
import ipfms.stripes.util.Configuration;
import ipfms.stripes.util.FileUtil;
import ipfms.workflow.Workflow;
import ipfms.workflow.WorkflowService;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.FileBean;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 *
 * @author fikri
 */
@UrlBinding("/property")
public class PropertyAction extends BaseActionBean{
    
    private Building building;    
    
    @Inject BuildingManager buildingManager;
    
    @Inject Configuration conf;
    
    @Inject Workflow workflow;
    
    @Inject WorkflowService workflowService;
    
    @Inject InboxManager inboxManager;
    
    private List<FileBean> listOfImages;
    
    private static final Logger LOG = Logger.getLogger(PropertyAction.class);
    
    @DefaultHandler
    public Resolution showForm() {
        return new JSP("property/property_form.jsp");
    }
    
    public Resolution save() {
        
        String taskId = (String) getContext().getRequest().getSession().getAttribute("taskId");
        
        Map<String,Object> input = new HashMap<String,Object>(); 
        
        String dms_path = conf.getProperty("document.path");
        Pengguna pengguna = getContext().getCurrentUser();        
        
        if (building != null) {
            LOG.info("desc == " + building.getBuidingDesc());
            InfoAudit ia = new InfoAudit();            
            ia.setDimasukOleh(pengguna);
            ia.setTarikhMasuk(new Date());
            building.setInfoAufit(ia);        
            buildingManager.saveOrUpdate(building);
                        
            
            //workflow.. beware of steps....
            //01 owner
            //02 sales
            //03 pmo
            //04 agent
            
//            input.put("idBuilding",String.valueOf(building.getIdBuilding()) );
//            input.put("fromUserId", pengguna.getIdPengguna());
//            if (pengguna.getKodJenisPengguna().getCode().equals("01") ) {
//                building.setPublish('T');
//                workflow.doAction(0, input);
//            } else if (pengguna.getKodJenisPengguna().getCode().equals("02") ) {
//                building.setPublish('T');
//                workflow.doAction(1, input);
//            } else if (pengguna.getKodJenisPengguna().getCode().equals("03") ) {
//                building.setPublish('Y');
//                input.put("publish", "Y");
//                workflow.doAction(2, input);
//            } else if (pengguna.getKodJenisPengguna().getCode().equals("04") ) {
//                building.setPublish('Y');
//                input.put("publish", "Y");
//                workflow.doAction(3, input);
//            }
            
            
            if (StringUtils.isBlank(taskId)) {
                input.put("idBuilding",String.valueOf(building.getIdBuilding()) );
                input.put("fromUserId", pengguna.getIdPengguna());
                String id = workflowService.initiateWorkflow("marketing", input);
                Inbox inbox = new Inbox();
//                inbox.setIdInbox(Integer.parseInt(id));
                inbox.setBuilding(building);
                inbox.setActive('Y');
                inbox.setInfoAudit(ia);
                inbox.setWorkflowId(id);
                inboxManager.save(inbox);
            } else {
                workflowService.complete(taskId);
            }         
        }        
        
        if (listOfImages != null && !listOfImages.isEmpty()) {
            InfoAudit ia = new InfoAudit();
            ia.setDimasukOleh(pengguna);
            ia.setTarikhMasuk(new Date());
            FileUtil fileUtil = new FileUtil(dms_path);
            
            for (FileBean image : listOfImages ) {
                String path = image.getFileName(); //String.valueOf(building.getIdBuilding()) + File.separator + image.getFileName();
                BuildingImg doc = new BuildingImg();
                String filename = image.getFileName().substring(0, image.getFileName().lastIndexOf("."));
                doc.setBuilding(building);
                doc.setInfoAufit(ia);
                doc.setImgName(filename);
                doc.setImgPath(path);    
                doc.setFormat(image.getContentType());
                buildingManager.saveOrUpdateImg(doc);
                try {
                    fileUtil.saveFile(image.getFileName(), image.getInputStream()); //fixme
                } catch (Exception ex) {
                    LOG.error(ex);
                }                
            }
        }
        return new RedirectResolution(PropertyAction.class, "viewDetail")
                .addParameter("idBuilding", building.getIdBuilding()).addParameter("new", true);
    }
    
    public Resolution viewMapForm() {
        String idBuilding = getContext().getRequest().getParameter("idBuilding");
        if (StringUtils.isNotBlank(idBuilding)) getContext().getRequest().setAttribute("idBuilding", idBuilding);
        return new JSP("property/map_enquiry.jsp").addParameter("popup", "true");
    }
    
    public Resolution saveLocation() {
        String result = "0";
        String idBuilding = getContext().getRequest().getParameter("idBuilding");
        String location = getContext().getRequest().getParameter("location");
        
        if (StringUtils.isNotBlank(idBuilding)) {
            building = buildingManager.findById(Integer.parseInt(idBuilding));
            if (building != null) {
                building.setMapLocation("111");
                buildingManager.saveOrUpdate(building);
                result = "1";
            }
            building = buildingManager.findById(Integer.parseInt(idBuilding));
            LOG.info("location " + building.getMapLocation());
        }
        return new StreamingResolution("text/plain", result);
    }
    
    public Resolution viewDetail() {
        String idBuilding = getContext().getRequest().getParameter("idBuilding");
        String newStr = getContext().getRequest().getParameter("new");
        
        if (StringUtils.isNotBlank(idBuilding)) {
            building = buildingManager.findById(Integer.valueOf(idBuilding));
        }
        
        if (StringUtils.isBlank(newStr))
            getContext().getRequest().setAttribute("enquiry", true);
        return new JSP("property/property_detail.jsp");
    }
    
    public Resolution enquiry() {
        String idBuilding = getContext().getRequest().getParameter("idBuilding");
        
        
        if (StringUtils.isNotBlank(idBuilding)) {
            building = buildingManager.findById(Integer.valueOf(idBuilding));
        }
        
        return new JSP("property/enquiry.jsp");
    }
    
    public Resolution editDetail() {
        String idBuilding = getContext().getRequest().getParameter("idBuilding");
        String taskId = getContext().getRequest().getParameter("taskId");
        
        Pengguna pengguna = getContext().getCurrentUser(); 
        
        
        if (StringUtils.isNotBlank(idBuilding)) {
            building = buildingManager.findById(Integer.valueOf(idBuilding));
            LOG.info("location = " + building.getMapLocation());
            
//            List<PenggunaPeranan> senaraiPeranan = pengguna.getSenaraiPeranan();
            
            
//            for (PenggunaPeranan pp : senaraiPeranan) {
//                if (pp.getPeranan() == null) continue;                
//                Inbox inbox = inboxManager.getWorkflow(pp.getPeranan().getDesc(), idBuilding);
//                if (inbox == null) continue;
//                //acquire                
//                inbox.setUserId(pengguna);
//                inbox.getInfoAudit().setDiKemaskiniOleh(pengguna);
//                inbox.getInfoAudit().setTarikhKemaskini(new Date());
//                inboxManager.save(inbox);
//                break;
//            }
            
            
        }
        
        if (StringUtils.isNotBlank(taskId)) {
            getContext().getRequest().getSession().setAttribute("taskId", taskId);
            Task task = workflowService.getTask(taskId);
            if (task != null) {
                String assignee = task.getAssignee();
                if (StringUtils.isNotBlank(assignee)) {
                    return new JSP("property/property_form.jsp");
                } else {
                    getContext().getRequest().setAttribute("claim", true);
                    return new JSP("property/property_detail.jsp");
                }
            }
        }
        return new JSP("property/property_detail.jsp");
    }
    
    public Resolution claim () {
        String idBuilding = getContext().getRequest().getParameter("idBuilding");
        if (StringUtils.isNotBlank(idBuilding)) {
            Inbox inbox = inboxManager.getInbox(idBuilding);
            if (inbox != null) {
                Pengguna pengguna = getContext().getCurrentUser(); 
                String taskId = inbox.getWorkflowId();
                workflowService.acquireTask(taskId, pengguna.getIdPengguna());
            }
            building = buildingManager.findById(Integer.valueOf(idBuilding));
        }
        return new JSP("property/property_form.jsp");
    }
    

    public Building getBuilding() {
        return building;
    }

    public void setBuilding(Building building) {
        this.building = building;
    }

    public List<FileBean> getListOfImages() {
        return listOfImages;
    }

    public void setListOfImages(List<FileBean> listOfImages) {
        this.listOfImages = listOfImages;
    }
    
}
